#include "CachedAddressValidatorWin.h"


const bool CachedAddressValidatorWin::isAddressValid( const address_t addr )
{
	if (inBoundsCache(addr))
	{
		return true;
	}

	MEMORY_BASIC_INFORMATION info = {};
	if (!::VirtualQueryEx(proc->native().get(), (LPCVOID)addr, &info, sizeof(info)))
		return false;

	if (info.State & MEM_COMMIT) // dunno if thats enough checking
		bounds_cache.push_back(MemoryBounds::fromLength((address_t)info.BaseAddress, (address_t)info.RegionSize));

	return inBoundsCache(addr);
}

void CachedAddressValidatorWin::reset()
{
	bounds_cache.erase(bounds_cache.begin(), bounds_cache.end());
}

bool CachedAddressValidatorWin::inBoundsCache( address_t addr )
{
	for (auto it = bounds_cache.cbegin(); it != bounds_cache.end(); it++)
	{
		if (it->contains(addr))
			return true;
	}
	return false;
}

CachedAddressValidatorWin::CachedAddressValidatorWin( const ProcessPtr proc_ ) : proc(proc_)
{

}
